from cProfile import label
from dataclasses import field

from django import forms
from django.shortcuts import HttpResponse, render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.template.defaultfilters import title

from app01 import models
from app01.utils.encrypt import md5

"""
    管理员管理模块
"""


def admin_list(request):
    """管理员数据列表"""

    search_dict = {}
    search_value = request.GET.get('search', '').strip()
    if search_value:
        search_dict['username'] = search_value

    # 获取并验证分页参数
    try:
        page = max(1, int(request.GET.get('page', 1)))
    except ValueError:
        page = 1

    try:
        limit = max(1, min(100, int(request.GET.get('limit', 10))))
    except ValueError:
        limit = 10

    # 查询数据并排序
    queryset = models.Admin.objects.filter(**search_dict).order_by('id')

    # 使用Django的Paginator进行分页
    paginator = Paginator(queryset, limit)
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    context = {
        'data_list': data_list,
        'search_value': search_value,
        'totals': paginator.count,
        'current_page': data_list.number,
        'page_size': limit,
        'total_pages': paginator.num_pages,
    }
    return render(request, 'admin/list.html', context)


class AdminModelForm(forms.ModelForm):
    """定义一个类去继承forms.ModelForm"""
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ['username', 'password']  # 字段名
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    # 执行init时,重新定义父类的init方法
    def __init__(self, *args, **kwargs):
        super(AdminModelForm, self).__init__(*args, **kwargs)  # 正确地调用父类的构造函数
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input", "placeholder": field.label, "lay-affix": "clear",
                                  "autocomplete": "off"}

    def clean_password(self):
        # 我这里拿到password后，直接加密了
        pwd = self.cleaned_data.get("password")
        return md5(pwd)  # 加密存储

    def clean_confirm_password(self):
        # 所以，这里拿到的 password 其实已经是加密后的
        print(self.cleaned_data)
        pass_word_str = self.cleaned_data['password']
        confirm_pass_word_str = md5(self.cleaned_data['confirm_password'])
        if confirm_pass_word_str != pass_word_str:
            raise ValidationError('密码不一致,请确认密码')
        return confirm_pass_word_str  # 返回什么，库里就存什么


def admin_add(request):
    """添加用户使用ModelForm组件"""
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'public/add.html', {"title": "新建管理员", "form": form})
    # 用户post提交数据，开始数据校验
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()  # 数据保存
        return redirect('/admin/list/')
    else:
        # 数据校验失败，就会在这里执行
        print(form.errors)
        return render(request, 'public/add.html', {"title": "新建管理员", "form": form})


class AdminEditModelForm(forms.ModelForm):
    """定义一个类去继承forms.ModelForm"""

    class Meta:
        model = models.Admin
        fields = ['username']  # 字段名

    # 执行init时,重新定义父类的init方法
    def __init__(self, *args, **kwargs):
        super(AdminEditModelForm, self).__init__(*args, **kwargs)  # 正确地调用父类的构造函数
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input", "placeholder": field.label, "lay-affix": "clear",
                                  "autocomplete": "off"}


def admin_edit(request, id):
    """管理员账号编辑"""
    """编辑账号使用ModelForm组件"""
    row_obj = models.Admin.objects.filter(id=id).first()  # 查询对应数据
    if not row_obj:
        return render(request, 'error-page/error.html', {"msg": "数据不存在"})
    if request.method == 'GET':
        form = AdminEditModelForm(instance=row_obj)  # 让实例等于查询的结果，双向绑定
        return render(request, 'public/add.html', {"form": form, "title": "编辑用户信息"})

    # 开始数据校验
    form = AdminEditModelForm(data=request.POST, instance=row_obj)  # 这样写就是，我拿到对应id的数据，然后使用MoelForm来更新
    if form.is_valid():
        # print(form.cleaned_data)
        # 默认保存的是用户输入的所有数据，如果表里有个特殊字段，我们要写入数据可以 这样
        # form.instance.字段名 = 字段值
        # 如果数据校验通过，就会在这里执行
        form.save()  # 数据保存
        return redirect('/admin/list/')
    else:
        # 数据校验失败，就会在这里执行
        print(form.errors)
        return render(request, 'public/add.html', {"form": form,"title": "编辑用户信息"})


def admin_delete(request):
    """管理员账号"""
    id = request.GET.get('id')
    models.Admin.objects.filter(id=id).delete()
    return redirect('/admin/list/')


class AdminResetModelForm(forms.ModelForm):
    """定义一个类去继承forms.ModelForm"""
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(render_value=True))

    class Meta:
        model = models.Admin
        fields = ['password']  # 字段名
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    # 执行init时,重新定义父类的init方法
    def __init__(self, *args, **kwargs):
        super(AdminResetModelForm, self).__init__(*args, **kwargs)  # 正确地调用父类的构造函数
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "layui-input", "placeholder": field.label, "lay-affix": "clear",
                                  "autocomplete": "off"}

    def clean_password(self):
        # 我这里拿到password后，直接加密了
        pwd = self.cleaned_data["password"]
        return md5(pwd)  # 加密存储

    def clean_confirm_password(self):
        # 所以，这里拿到的 password 其实已经是加密后的
        print(self.cleaned_data)
        pass_word_str = self.cleaned_data['password']
        confirm_pass_word_str = md5(self.cleaned_data['confirm_password'])
        # 去数据库校验一下，当前id记录的密码md5 后 与新设置的密码md5 是否一样
        exists = models.Admin.objects.filter(id=self.instance.pk,password=pass_word_str).exists()
        if exists:
            raise ValidationError('新密码不能与旧密码一样,请重新设置新密码')

        if confirm_pass_word_str != pass_word_str:
            raise ValidationError('密码不一致,请确认密码')

        return confirm_pass_word_str  # 返回什么，库里就存什么

def admin_reset(request,id):
    """管理员账号密码重置"""
    row_obj = models.Admin.objects.filter(id=id).first()  # 查询对应数据
    if not row_obj:
        return render(request, 'error-page/error.html', {"msg": "该账号不存在"})

    # 最简单的版本 S
    # password = md5('123456a')
    # models.Admin.objects.filter(id=id).update(password=password)
    # return redirect('/admin/list/')
    # 最简单的版本 E

    title = "重置密码-{}".format(row_obj.username)
    if request.method == 'GET':
        form = AdminResetModelForm()  # 让实例等于查询的结果，双向绑定
        return render(request, 'public/add.html', {"title": title, "form": form})

    # 用户post提交数据，开始数据校验
    form = AdminResetModelForm(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()  # 数据保存
        return redirect('/admin/list/')
    else:
        # 数据校验失败，就会在这里执行
        print(form.errors)
        return render(request, 'public/add.html', {"title": title, "form": form})

